package com.tensquare.friend.controller;

import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.pojo.NoFriend;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/12/23 15:57
 */
@RestController
@RequestMapping("friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    @Autowired
    private NoFriendService noFriendService;
    //1.添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid,@PathVariable int type){
        //1.1)从请求作用域中得到claims的值
        Claims claims = (Claims) request.getAttribute("claims");
        //1.2)判断是否有值
        if(claims != null){
            //1.3)根据类型判断是否是加入好友
            if (type == 1){      //好友
                    //1.3.1)添加好友
                    int count = friendService.addFriend(claims.getId(),friendid);
                    //1.3.2)更新粉丝数与关注数
                    //① 增加自己的关注数
                    userClient.incFollow(claims.getId(),1);
                    //② 增加对方的粉丝数
                    userClient.incFans(friendid,1);
                    if(count == 0){
                        return new Result(false, StatusCode.REPERROR,"重复添加好友！");
                    }


            }else if(type == 2){        //代表非好友
                noFriendService.addNoFriend(claims.getId(),friendid);
            }
        }
        return new Result(true,StatusCode.OK,"添加好友成功！");

    }

    //2.删除好友
    @DeleteMapping("{friendid}")
    public Result deleteFriend(@PathVariable String friendid){
        //2.1)得到当前登录用户id
        Claims claims = (Claims) request.getAttribute("claims");
        //2.2)判断是否有值
        if(claims != null){
            String userId = claims.getId(); //用户id
            //2.3)删除好友
            friendService.delete(userId,friendid);
            //2.4)减少自身的关注数
            userClient.incFollow(claims.getId(),-1);
            //2.5)减少对方的粉丝数
            userClient.incFans(friendid,-1);

            return new Result(true,StatusCode.OK,"删除好友成功！");
        }
            return new Result(false,StatusCode.ACCESSERROR,"无权删除用户！");


    }
}
